import 'dart:async';
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:flutter/material.dart';

import '../http/HttpCode.dart';
import '../resources.dart';

export '../http/HttpCode.dart';

///接口返回数据key
// {"ret":10000,"msg":"认证成功，将返回权限数据","success":true,"content":{"token":"MGRkY2IyMWQ1NTk1NDI0YmJlNTVjMTRiNDA2MzkzZmU",
// "privileges":"0","newPlay":"0","serverTime":"2025-01-17 23:33:56","bindPhone":"1","phone":"15804027745",
// "bindDevice":"1","isFinishInitPassword":0,"isNeedModifyPassword":0,"quato":100000.0}}
const String codeKey = 'code';
const String msgKey = 'msg';
const String dataKey = 'data';

class Request {
  Dio? dio;
  static Request? _instance;

  factory Request() => _getInstance();

  static Request _getInstance() {
    _instance ??= Request._internal();
    return _instance!;
  }

  Request._internal() {
    dio ??= Dio(BaseOptions(
      baseUrl: '',
      validateStatus: (status) => true, // 忽略http状态码验证
    ));

    ///处理不可信的证书
    if (isAndroid || isIOS) {
      if (dio!.httpClientAdapter is IOHttpClientAdapter) {
        (dio!.httpClientAdapter as IOHttpClientAdapter).onHttpClientCreate =
            (client) {
          client.badCertificateCallback = (cert, host, port) => true;
          return client;
        };
      }
    }
    dio!.options.connectTimeout = const Duration(milliseconds: 10000);
    dio!.options.receiveTimeout = const Duration(milliseconds: 10000);
    dio!.options.responseType = ResponseType.plain;
    // dio!.interceptors.add(RequestLog());
    // dio!.interceptors.add(LogInterceptor(
    //     requestBody: CommonUtils.isDebug,
    //     responseBody: CommonUtils.isDebug,
    //     responseHeader: CommonUtils.isDebug,
    //     requestHeader: CommonUtils.isDebug,
    //     request: CommonUtils.isDebug));
  }

  static Request get instance => _getInstance();

  static Future<HttpResult> request(
    String path, {
    String method = 'POST',
    Map<String, dynamic> data = const {},
    bool isJson = true,
    bool errorToast = true,
  }) async {
    Map<String, dynamic> headerMap = {};

    Dio dio = Request.instance.dio!;
    Options options = Options(
        method: method,
        contentType:
            isJson ? 'application/json' : 'application/x-www-form-urlencoded',
        headers: headerMap);

    int statusCode = HttpCode.HTTP_NONE;
    String statusMessage = word.network_error;
    Map<String, dynamic> content = {};
    bool success = false;
    try {
      Response response = await dio.request(
        path,
        data: method != 'GET' ? data : null,
        queryParameters: data,
        options: options,
      );

      statusCode = response.statusCode ?? HttpCode.HTTP_NONE;
      var tempData = {};
      if (response.data != null) {
        if (response.data is String) {
          try {
            tempData = json.decode(response.data);
          } catch (e) {}
        } else if (response.data is Map) {
          tempData = response.data;
        }
      }

      var code = tempData[codeKey];
      statusMessage = tempData[msgKey];
      if (code != null && code is int) {
        statusCode = code;
        if (statusCode == 200) {
          success = true;
          content = tempData[dataKey] ?? {};
        }
      }
    } on DioException catch (e) {
      if (e.response != null) {
        statusCode = e.response!.statusCode ?? HttpCode.HTTP_DATE_ERROR;
        statusMessage = e.response!.statusMessage ?? e.message ?? '';
      } else {
        statusCode = HttpCode.HTTP_ERROR;
        statusMessage = word.network_error;
      }
    }

    return HttpResult(
        statusCode: statusCode,
        statusMessage: statusMessage,
        content: content,
        success: success);
  }

// static Future<String> download(
//     {required String url,
//     required Function(double progress) onProgress}) async {
//   String path = await FileUtils.getFilePath(url);
//   Dio dio = Dio();
//
//   ///处理不可信的证书
//   (dio!.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
//       (client) {
//     client.badCertificateCallback = (cert, host, port) => true;
//     return client;
//   };
//   Response response =
//       await dio.download(url, path, onReceiveProgress: (received, total) {
//     if (total != -1) {
//       onProgress(received / total);
//     }
//   }).catchError((catchError) {
//     print('catchError  $catchError');
//   });
//   return response.statusCode == 200 ? path : '';
// }
}

class HttpResult {
  int statusCode;
  String statusMessage;
  bool success;
  Map<String, dynamic> content;

  HttpResult({
    required this.statusCode,
    required this.statusMessage,
    required this.success,
    required this.content,
  });

  @override
  String toString() {
    return 'NetResult：statusCode: $statusCode success: $success \n'
        'NetResult: statusMessage: $statusMessage \n'
        'NetResult: content: ${content.toString()}';
  }
}
